package com.xpqh.ksg.modular.core.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Reader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import com.xpqh.ksg.common.persistence.dao.*;
import com.xpqh.ksg.common.persistence.model.KsgCaseInfo;
import com.xpqh.ksg.common.persistence.model.KsgProductInfo;
import com.xpqh.ksg.common.persistence.model.KsgStockInfo;
import com.xpqh.ksg.common.persistence.model.KsgStoreInfo;
import com.xpqh.ksg.common.utils.HttpUtils;
import com.xpqh.ksg.modular.core.dto.*;
import common.utils.ImageDownloader;
import common.utils.StringUtils;
import net.sf.json.JSONArray;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CoreService {


    @Autowired
    private KsgBrandInfoMapper brandInfoMapper;

    @Autowired
    private KsgSeriesInfoMapper seriesInfoMapper;

    @Autowired
    private KsgProductInfoMapper productInfoMapper;

    @Autowired
    private KsgSeriesDetailsMapper detailsMapper;

    @Autowired
    private KsgStockInfoMapper stockInfoMapper;

    @Autowired
    private KsgWarrantyInfoMapper warrantyInfoMapper;
    public List<KsgBrandListRespDTO> getBrandList() {
        return brandInfoMapper.getBrandList();
    }

    public List<KsgBrandGroupListRespDTO> getBrandGroupList() {
        List<KsgBrandListRespDTO> brandList = brandInfoMapper.getBrandList();
        List<KsgBrandGroupListRespDTO> brandGroupList = brandInfoMapper.getBrandGroupList();
        List<KsgBrandListRespDTO> brandList2 = new ArrayList<>();
        for (KsgBrandGroupListRespDTO ksgBrandGroupListRespDTO : brandGroupList) {
            brandList2 = new ArrayList<>();
            for (KsgBrandListRespDTO ksgBrandListRespDTO : brandList) {
                if (ksgBrandGroupListRespDTO.getGroupName().equals(ksgBrandListRespDTO.getInitialFirst())) {
                    brandList2.add(ksgBrandListRespDTO);
                }
            }
            ksgBrandGroupListRespDTO.setBrandList(brandList2);
        }

        return brandGroupList;
    }

    public List<KsgSeriesInfoRespDTO> series(SeriesListReqDTO req) {
        return  seriesInfoMapper.getSeriesList(req.getBrandId());
    }
    public Object getProductNameList(Integer type,Integer channelType,Integer productType) {
        if (type == 1) {
            return productInfoMapper.getProductNameListAll();
        }
        if (null == channelType) {
            return productInfoMapper.getProductNameList();
        }else {
            List<KsgProductListRespDTO> productList = productInfoMapper.getProductList(productType,channelType);
            for (KsgProductListRespDTO respDTO : productList) {
                respDTO.setProductList(productInfoMapper.getProductNameListByChannel(respDTO.getSeriesName(),channelType,productType));
            }
            return productList;
        }
    }

    public KsgPriceListRespDTO getPriceInfo(String carSeriesId, String productId) {
        KsgPriceListRespDTO priceInfo = new KsgPriceListRespDTO();
        if (StringUtils.isNotBlank(carSeriesId)) {
            priceInfo = detailsMapper.getPriceInfo(carSeriesId, productId);
            if (null == priceInfo) {
                CarLvInfo carLvInfo = seriesInfoMapper.getCarLvInfo(carSeriesId);
                if (null != carLvInfo) {
                    priceInfo = detailsMapper.getCyPriceInfo(Integer.parseInt(productId), carLvInfo.getCarLv(), carLvInfo.getPriceLv());
                }
            }
        } else {
            priceInfo= detailsMapper.getPriceInfoByType(productId);
        }
        if (null == priceInfo) {
            priceInfo= detailsMapper.getPriceInfoByType(productId);
        }
        if (priceInfo != null) {
            priceInfo.setStorePhone("13906008177");
        }
        return priceInfo;
    }

    public List<KsgWindowTypeListRespDTO> getWindowTypeList(Integer channelType) {
        if (null == channelType) {
            return productInfoMapper.getWindowTypeList();
        }else {
            return productInfoMapper.getWindowTypeListByChannelType(channelType);
        }
    }
    public KsgWindowPriceListRespDTO getWindowPrice(String carSeriesId, String productIdList) {
        List<KsgWindowPriceRespDTO> windowPrice = new ArrayList<>();
        if (StringUtils.isNotBlank(carSeriesId)) {
            windowPrice =  productInfoMapper.getWindowPrice(carSeriesId, productIdList);
        }else {
            windowPrice =  productInfoMapper.getWindowPriceByType(productIdList);
        }
        KsgWindowPriceListRespDTO respDTO = new KsgWindowPriceListRespDTO();
        respDTO.setPriceList(windowPrice);
        BigDecimal countPrice = new BigDecimal("0");
        for (KsgWindowPriceRespDTO ksgWindowPriceRespDTO : windowPrice) {
            countPrice = countPrice.add(ksgWindowPriceRespDTO.getPrice());
        }
        respDTO.setCountPrice(countPrice);
        return respDTO;
    }
    public List<KsgProductSeriesListRespDTO> getProductSeriesList(Integer productId) {
        return  productInfoMapper.getProductSeriesList( productId);
    }
    public String ocrVIN(String picture) {
        return getVin(picture);
    }
    public  String getVin(String imageUrl) {
        String host = "https://vin.market.alicloudapi.com";
        String path = "/api/predict/ocr_vin";
        String appcode = "fb7376b176b74d9b94de197ea2ec351c";
        String imgFile = imageUrl;
        Boolean is_old_format = false;//如果文档的输入中含有inputs字段，设置为True， 否则设置为False
        //请根据线上文档修改configure字段
        // JSONObject configObj = new JSONObject();
        // configObj.put("multi_crop", false);
        // String config_str = configObj.toString();
        //            configObj.put("min_size", 5);
        String config_str = "";

        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);

        Map<String, String> querys = new HashMap<String, String>();
        // 拼装请求body的json字符串
        com.alibaba.fastjson.JSONObject requestObj = new com.alibaba.fastjson.JSONObject();
        try {
            if(is_old_format) {
                com.alibaba.fastjson.JSONObject obj = new com.alibaba.fastjson.JSONObject();
                obj.put("image", getParam(50, imgFile));
                if(config_str.length() > 0) {
                    obj.put("configure", getParam(50, config_str));
                }
                JSONArray inputArray = new JSONArray();
                inputArray.add(obj);
                requestObj.put("inputs", inputArray);
            }else{
                requestObj.put("image", imgFile);
                if(config_str.length() > 0) {
                    requestObj.put("configure", config_str);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
            return "";
        }
        String bodys = requestObj.toString();

        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            int stat = response.getStatusLine().getStatusCode();
            if(stat != 200){
                System.out.println("Http code: " + stat);
                System.out.println("http header error msg: "+ response.getFirstHeader("X-Ca-Error-Message"));
                System.out.println("Http body error msg:" + EntityUtils.toString(response.getEntity()));
                return null;
            }
            String res = EntityUtils.toString(response.getEntity());
            com.alibaba.fastjson.JSONObject res_obj = JSON.parseObject(res);
            if(is_old_format) {
                com.alibaba.fastjson.JSONArray outputArray = res_obj.getJSONArray("outputs");
                String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue");
                com.alibaba.fastjson.JSONObject out = JSON.parseObject(output);
                System.out.println(out.toJSONString());
                return out.getString("vin");
            }else{
                System.out.println(res_obj.toJSONString());
                return res_obj.getString("vin");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public String barCode(String picture,Integer userid) {
        try {
            File barcodeFile = ImageDownloader.urlToFile(picture);
            // 验证文件是否存在
            if (!barcodeFile.exists()) {
                return "错误：文件不存在 ";
            }
            try {
                // 读取条形码图片
                java.awt.image.BufferedImage image = ImageIO.read(barcodeFile);

                // 创建二进制位图对象
                BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
                BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

                // 创建条形码阅读器
                Reader reader = new MultiFormatReader();

                // 解码条形码
                Result result = reader.decode(bitmap);

                // 输出条形码内容和格式
                String text = result.getText();
                if (StringUtils.isNotBlank(text)) {
                    KsgStockInfo bySignalId = stockInfoMapper.getBySignalId(text);
                    if (bySignalId == null) {
                        return "错误：未找到卷芯码信息";
                    }
                    if (!StringUtils.isNotBlank(bySignalId.getStoreId()) || "111".equals(bySignalId.getStoreId())) {
                        KsgStoreInfo storeInfo = warrantyInfoMapper.getStoreInfo(userid);
                        if (storeInfo == null) {
                            return "未找到对应门店";
                        }
                        stockInfoMapper.updateStockDistributeType(text,storeInfo.getAutoId());
                        stockInfoMapper.insertStockRecord(text,storeInfo.getAutoId(),storeInfo.getUserCode(),"扫码入库");
                    }else {
                        return "该产品已入库";
                    }
                }else {
                    return "未找到对应的产品";
                }
            } catch (IOException e) {
                return "错误：读取图片时出错 - " + e.getMessage();
            } catch (Exception e) {
                return "发生未知错误: " + e.getMessage();
            }
        }catch (Exception e) {
            return "错误：图片下载失败";
        }

        return "操作成功";
    }


    /*
     * 获取参数的json对象
     */
    public static com.alibaba.fastjson.JSONObject getParam(int type, String dataValue) {
        com.alibaba.fastjson.JSONObject obj = new com.alibaba.fastjson.JSONObject();
        try {
            obj.put("dataType", type);
            obj.put("dataValue", dataValue);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return obj;
    }

    public Integer AddStockInfo(KsgAddStockInfoReqDTO reqDTO) {
        Integer num = 0;
        List<String> productInfoList = reqDTO.getProductInfoList();
        for (String s : productInfoList) {
            s = s.replace("－","-");
            brandInfoMapper.updateStockInfo(reqDTO.getStoreId(),s);
            brandInfoMapper.insertStockLog(reqDTO.getStoreId(),s);
            brandInfoMapper.insertStockRecord(reqDTO.getStoreId(),s,reqDTO.getUserid());
            num++;
        }
        return num;
    }

    public Integer afterSales(KsgAfterSalesReqDTO reqDTO) {
        return brandInfoMapper.afterSales(reqDTO.getPhone(),reqDTO.getNote(),reqDTO.getPicture());
    }
    public List<KsgBannerListReqDTO> getBannerList(String language) {
        return brandInfoMapper.getBannerList(language);
    }

    public List<KsgCountryListRespDTO> getCountryList() {
        return brandInfoMapper.getCountryList();
    }
    public List<KsgCaseInfo> getCaseListC(String language) {
        return brandInfoMapper.getCaseListByHomeByPc(language);
    }

    public List<KsgNewsListRespDTO> getNewsListByHome() {
        return brandInfoMapper.getNewsListByHome();
    }
    public List<KsgStoreInfoListRespDTO> getStoreInfoListByHome() {
        return brandInfoMapper.getStoreInfoList2ByHome();
    }

}

